package com.daify.threadlearn.chapter01.executorService;


import java.util.concurrent.RecursiveTask;

/**
 *
 * @author daify
 * @date 2019-06-20 10:38
 **/
public class JoinTask extends RecursiveTask<Integer> {
    //每个小任务 最多只累加20个数
    private static final int THRESHOLD = 10;
    private int array[];
    private int start;
    private int end;
    
    
    /**
     * 执行计算的规则
     * The main computation performed by this task.
     * @return the result of the computation
     */
    @Override 
    protected Integer compute() {
        int sum =0;
        // 任务已经拆分足够细了
        if (end - start < THRESHOLD){
            for(int i = start; i < end; i++){
                sum += array[i];
            }
            System.out.println(Thread.currentThread().getName() + "线程开始执行计算任务");
            return sum;
        } else { // 需要继续拆分任务
            int middle = (start + end) / 2;
            JoinTask left = new JoinTask(array, start, middle);
            JoinTask right = new JoinTask(array, middle, end);
            // 并行执行两个小任务
            left.fork();
            right.fork();
            //把两个小任务累加的结果合并起来
            return left.join() + right.join();
        }
    }

    public JoinTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }
}
